<template>
    <div class="card">
        <div class="card-body">
            <div class="row">
                <div class="col-3 img-field">
                    <img class="img-fluid" :src="user.photo" alt="">
                </div>
                <div class="col-9">
                    <div class="username">{{ user.username }}</div>
                    <div class="fans">粉丝：{{ user.followerCount }}</div>
                    <button @click="follow" v-if="!is_me && !user.is_followed" type="button" class="btn btn-secondary btn-sm">+关注</button>
                    <button @click="unfollow" v-if="!is_me && user.is_followed" type="button" class="btn btn-secondary btn-sm">取消关注</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import $ from 'jquery';
import { useStore } from 'vuex';
import { computed } from 'vue';

export default {
    name: "UserProfileInfo",
    props: {
        user: {
            type: Object,
            required: true,
        },
    },
    setup(props, context) {
        const store = useStore();
        const follow = () => {
            $.ajax({
              url: "http://127.0.0.1:3005/myspace/follow/",
              type: "POST",
              data: {
                follow_id: store.state.user.id,
                target_id: props.user.id,
              },
              headers: {
                  'Authorization': "Bearer " + store.state.user.token,
              },
              success(resp) {
                console.log(resp);
                if (resp.error_message === "success") {
                    context.emit('follow');
                }
              }
            });
        };

        const unfollow = () => {
            $.ajax({
              url: "http://127.0.0.1:3005/myspace/unfollow/",
              type: "POST",
              data: {
                follow_id: store.state.user.id,
                target_id: props.user.id,
              },
              headers: {
                  'Authorization': "Bearer " + store.state.user.token,
              },
              success(resp) {
                console.log(resp);
                  if (resp.error_message === "success") {
                      context.emit('unfollow');
                  }
              }
            });
        }

        const is_me = computed(() => props.user.id === store.state.user.id);
        return {
            follow,
            unfollow,
            is_me,
        }
    }
}
</script>


<style scoped>
img {
    border-radius: 50%;
}

.username {
    font-weight: bold;
}

.fans {
    font-size: 12px;
    color: gray;
}

button {
    padding: 2px 4px;
    font-size: 12px;
}

.img-field {
    display: flex;
    flex-direction: column;
    justify-content: center;
}
</style>